"""
用户界面模块 - 处理所有GUI相关功能
"""
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
from datetime import datetime
import os


class AlarmClockUI:
    def __init__(self, root, alarm_manager, audio_controller):
        """初始化用户界面"""
        self.root = root
        self.alarm_manager = alarm_manager
        self.audio_controller = audio_controller
        
        self.alarm_volume = 50  # 默认音量
        
        # 设置窗口
        self.root.title("闹钟程序")
        self.root.geometry("850x650")
        self.root.resizable(False, False)
        
        # 设置UI
        self.setup_ui()
    
    def setup_ui(self):
        """设置用户界面"""
        # 标题
        title_label = tk.Label(self.root, text="⏰ 闹钟管理系统", 
                              font=("Microsoft YaHei", 20, "bold"), fg="#2c3e50")
        title_label.pack(pady=15)
        
        # 当前时间显示
        self.time_label = tk.Label(self.root, text="", 
                                   font=("Microsoft YaHei", 14), fg="#34495e")
        self.time_label.pack(pady=5)
        self.update_time_display()
        
        # 音量控制框架
        volume_frame = tk.LabelFrame(self.root, text="🔊 闹钟音量设置", 
                                     font=("Microsoft YaHei", 10, "bold"),
                                     padx=15, pady=10)
        volume_frame.pack(fill="x", padx=20, pady=10)
        
        tk.Label(volume_frame, text="音量:", font=("Microsoft YaHei", 9)).pack(side="left", padx=5)
        self.volume_scale = tk.Scale(volume_frame, from_=0, to=100, orient="horizontal",
                                     length=300, command=self.on_volume_change)
        self.volume_scale.set(self.alarm_volume)
        self.volume_scale.pack(side="left", padx=10)
        self.volume_label = tk.Label(volume_frame, text=f"{self.alarm_volume}%", 
                                     font=("Microsoft YaHei", 9, "bold"), fg="#e74c3c")
        self.volume_label.pack(side="left", padx=5)
        
        # 闹钟列表框架
        list_frame = tk.LabelFrame(self.root, text="📋 闹钟列表", 
                                   font=("Microsoft YaHei", 10, "bold"),
                                   padx=10, pady=10)
        list_frame.pack(fill="both", expand=True, padx=20, pady=10)
        
        # 创建Treeview
        columns = ("时间", "重复模式", "铃声", "状态")
        self.alarm_tree = ttk.Treeview(list_frame, columns=columns, show="headings", height=12)
        
        # 设置列
        self.alarm_tree.heading("时间", text="⏰ 时间")
        self.alarm_tree.heading("重复模式", text="🔄 重复模式")
        self.alarm_tree.heading("铃声", text="🎵 铃声")
        self.alarm_tree.heading("状态", text="📊 状态")
        
        self.alarm_tree.column("时间", width=100, anchor="center")
        self.alarm_tree.column("重复模式", width=250)
        self.alarm_tree.column("铃声", width=200)
        self.alarm_tree.column("状态", width=80, anchor="center")
        
        # 滚动条
        scrollbar = ttk.Scrollbar(list_frame, orient="vertical", command=self.alarm_tree.yview)
        scrollbar.pack(side="right", fill="y")
        self.alarm_tree.configure(yscrollcommand=scrollbar.set)
        self.alarm_tree.pack(side="left", fill="both", expand=True)
        
        # 按钮框架
        button_frame = tk.Frame(self.root)
        button_frame.pack(pady=15)
        
        buttons = [
            ("➕ 添加闹钟", self.add_alarm_dialog, "#27ae60"),
            ("✏️ 编辑闹钟", self.edit_alarm_dialog, "#3498db"),
            ("🗑️ 删除闹钟", self.delete_alarm, "#e74c3c"),
            ("🔄 切换状态", self.toggle_alarm, "#f39c12"),
            ("🎵 管理铃声", self.manage_ringtones, "#9b59b6")
        ]
        
        for text, command, color in buttons:
            btn = tk.Button(button_frame, text=text, command=command,
                          width=14, height=2, bg=color, fg="white",
                          font=("Microsoft YaHei", 9, "bold"),
                          relief=tk.RAISED, bd=2)
            btn.pack(side="left", padx=5)
        
        # 刷新闹钟列表
        self.refresh_alarm_list()
    
    def update_time_display(self):
        """更新当前时间显示"""
        current_time = datetime.now().strftime("%Y年%m月%d日 %H:%M:%S %A")
        weekday_map = {
            "Monday": "星期一", "Tuesday": "星期二", "Wednesday": "星期三",
            "Thursday": "星期四", "Friday": "星期五", "Saturday": "星期六", "Sunday": "星期日"
        }
        for en, zh in weekday_map.items():
            current_time = current_time.replace(en, zh)
        
        self.time_label.config(text=f"当前时间: {current_time}")
        self.root.after(1000, self.update_time_display)
    
    def on_volume_change(self, value):
        """音量滑块变化处理"""
        self.alarm_volume = int(float(value))
        self.volume_label.config(text=f"{self.alarm_volume}%")
    
    def get_alarm_volume(self):
        """获取当前设置的闹钟音量"""
        return self.alarm_volume
    
    def add_alarm_dialog(self):
        """显示添加闹钟对话框"""
        self.show_alarm_dialog(mode="add")
    
    def edit_alarm_dialog(self):
        """显示编辑闹钟对话框"""
        selection = self.alarm_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个闹钟")
            return
        
        index = self.alarm_tree.index(selection[0])
        self.show_alarm_dialog(mode="edit", alarm_index=index)
    
    def show_alarm_dialog(self, mode="add", alarm_index=None):
        """显示闹钟配置对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title("➕ 添加闹钟" if mode == "add" else "✏️ 编辑闹钟")
        dialog.geometry("450x650")  # 增加高度从500到650
        dialog.resizable(True, True)  # 允许调整大小
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 加载现有闹钟数据（如果是编辑模式）
        alarm_data = None
        if mode == "edit" and alarm_index is not None:
            alarm_data = self.alarm_manager.get_alarm(alarm_index)
        
        # 时间设置
        time_frame = tk.LabelFrame(dialog, text="⏰ 时间设置", 
                                   font=("Microsoft YaHei", 10, "bold"),
                                   padx=15, pady=15)
        time_frame.pack(fill="x", padx=20, pady=10)
        
        # 添加说明文字
        tk.Label(time_frame, text="请设置闹钟响铃的时间（24小时制）", 
                font=("Microsoft YaHei", 8), fg="#7f8c8d").pack(pady=(0, 10))
        
        time_inner = tk.Frame(time_frame)
        time_inner.pack()
        
        tk.Label(time_inner, text="小时 (0-23):", font=("Microsoft YaHei", 9)).grid(row=0, column=0, padx=5, sticky="e")
        hour_var = tk.Spinbox(time_inner, from_=0, to=23, width=8, font=("Arial", 12), 
                             justify="center", wrap=True)
        hour_var.grid(row=0, column=1, padx=5)
        
        tk.Label(time_inner, text="分钟 (0-59):", font=("Microsoft YaHei", 9)).grid(row=0, column=2, padx=5, sticky="e")
        minute_var = tk.Spinbox(time_inner, from_=0, to=59, width=8, font=("Arial", 12),
                               justify="center", wrap=True)
        minute_var.grid(row=0, column=3, padx=5)
        
        # 设置默认值或加载现有数据
        if alarm_data:
            hour_var.delete(0, "end")
            hour_var.insert(0, alarm_data["hour"])
            minute_var.delete(0, "end")
            minute_var.insert(0, alarm_data["minute"])
        else:
            # 设置默认值为当前时间+1分钟
            from datetime import datetime, timedelta
            default_time = datetime.now() + timedelta(minutes=1)
            hour_var.delete(0, "end")
            hour_var.insert(0, default_time.hour)
            minute_var.delete(0, "end")
            minute_var.insert(0, default_time.minute)
        
        # 添加示例说明
        example_frame = tk.Frame(time_frame)
        example_frame.pack(pady=(10, 0))
        tk.Label(example_frame, text="💡 示例: 08:30 表示早上8点30分，14:00 表示下午2点",
                font=("Microsoft YaHei", 8), fg="#3498db").pack()
        
        # 重复模式
        repeat_frame = tk.LabelFrame(dialog, text="🔄 重复模式", 
                                     font=("Microsoft YaHei", 10, "bold"),
                                     padx=15, pady=10)
        repeat_frame.pack(fill="x", padx=20, pady=10)
        
        repeat_var = tk.StringVar(value=alarm_data["repeat"] if alarm_data else "一次")
        
        repeat_options = [
            ("⏱️ 一次", "一次"),
            ("📅 每天", "每天"),
            ("💼 工作日 (周一至周五)", "工作日"),
            ("🎉 周末 (周六、周日)", "周末")
        ]
        
        for text, value in repeat_options:
            tk.Radiobutton(repeat_frame, text=text, variable=repeat_var, value=value,
                          font=("Microsoft YaHei", 9)).pack(anchor="w", pady=2)
        
        # 自定义天数
        custom_frame = tk.Frame(repeat_frame)
        custom_frame.pack(fill="x", pady=5)
        
        tk.Radiobutton(custom_frame, text="📆 自定义:", variable=repeat_var, value="自定义",
                      font=("Microsoft YaHei", 9)).pack(anchor="w")
        
        days_frame = tk.Frame(custom_frame)
        days_frame.pack(fill="x", padx=20)
        
        day_vars = {}
        days = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
        for i, day in enumerate(days):
            var = tk.BooleanVar(value=False)
            if alarm_data and alarm_data["repeat"] == "自定义":
                var.set(day in alarm_data.get("custom_days", []))
            day_vars[day] = var
            cb = tk.Checkbutton(days_frame, text=day, variable=var,
                               font=("Microsoft YaHei", 8))
            cb.grid(row=i//4, column=i%4, sticky="w", padx=5, pady=2)
        
        # 铃声选择
        ringtone_frame = tk.LabelFrame(dialog, text="🎵 铃声选择", 
                                       font=("Microsoft YaHei", 10, "bold"),
                                       padx=15, pady=10)
        ringtone_frame.pack(fill="x", padx=20, pady=10)
        
        ringtones = self.audio_controller.get_available_ringtones()
        ringtone_var = tk.StringVar()
        ringtone_menu = None
        
        if ringtones:
            # 有铃声时使用OptionMenu
            default_ringtone = alarm_data["ringtone"] if alarm_data and alarm_data["ringtone"] in ringtones else ringtones[0]
            ringtone_var.set(default_ringtone)
            
            ringtone_menu = tk.OptionMenu(ringtone_frame, ringtone_var, *ringtones)
            ringtone_menu.config(width=35, font=("Microsoft YaHei", 10), 
                                bg="white", fg="#2c3e50", 
                                relief=tk.RAISED, bd=2)
            ringtone_menu.pack(pady=10, padx=10, fill="x")
        else:
            # 没有铃声时显示提示和快速添加按钮
            warning_frame = tk.Frame(ringtone_frame)
            warning_frame.pack(pady=5)
            
            tk.Label(warning_frame, text="⚠️ 铃声库为空，请添加铃声文件",
                    fg="#e74c3c", font=("Microsoft YaHei", 9)).pack()
            
            def quick_add_ringtone():
                files = filedialog.askopenfilenames(
                    title="选择铃声文件",
                    filetypes=[
                        ("音频文件", "*.mp3 *.wav *.ogg"),
                        ("MP3文件", "*.mp3"),
                        ("WAV文件", "*.wav"),
                        ("OGG文件", "*.ogg"),
                        ("所有文件", "*.*")
                    ]
                )
                
                if files:
                    count = 0
                    for file in files:
                        if self.audio_controller.add_ringtone(file):
                            count += 1
                    
                    if count > 0:
                        # 刷新铃声列表
                        new_ringtones = self.audio_controller.get_available_ringtones()
                        if new_ringtones:
                            ringtone_var.set(new_ringtones[0])
                            # 隐藏警告信息
                            warning_frame.pack_forget()
                            # 创建新的OptionMenu
                            new_menu = tk.OptionMenu(ringtone_frame, ringtone_var, *new_ringtones)
                            new_menu.config(width=35, font=("Microsoft YaHei", 9), bg="white")
                            new_menu.pack(pady=5, padx=10)
                        messagebox.showinfo("成功", f"已成功添加 {count} 个铃声")
            
            tk.Button(warning_frame, text="📁 立即添加铃声", command=quick_add_ringtone,
                     bg="#3498db", fg="white", font=("Microsoft YaHei", 9, "bold"),
                     padx=10, pady=5).pack(pady=5)
        
        # 保存和取消按钮
        button_frame = tk.Frame(dialog)
        button_frame.pack(pady=20)
        
        def save_alarm():
            try:
                hour = int(hour_var.get())
                minute = int(minute_var.get())
                
                if not (0 <= hour <= 23 and 0 <= minute <= 59):
                    messagebox.showerror("错误", "请输入有效的时间 (小时: 0-23, 分钟: 0-59)")
                    return
                
                repeat = repeat_var.get()
                custom_days = [day for day, var in day_vars.items() if var.get()] if repeat == "自定义" else []
                
                if repeat == "自定义" and not custom_days:
                    messagebox.showerror("错误", "自定义模式下请至少选择一天")
                    return
                
                ringtone = ringtone_var.get()
                if not ringtone:
                    messagebox.showerror("错误", "请选择铃声")
                    return
                
                if mode == "add":
                    self.alarm_manager.add_alarm(hour, minute, repeat, custom_days, ringtone, True)
                else:
                    enabled = alarm_data["enabled"] if alarm_data else True
                    self.alarm_manager.edit_alarm(alarm_index, hour, minute, repeat, custom_days, ringtone, enabled)
                
                self.refresh_alarm_list()
                dialog.destroy()
                messagebox.showinfo("成功", "闹钟已保存")
                
            except ValueError:
                messagebox.showerror("错误", "请输入有效的数字")
        
        tk.Button(button_frame, text="💾 保存", command=save_alarm, width=12, height=2,
                 bg="#27ae60", fg="white", font=("Microsoft YaHei", 10, "bold")).pack(side="left", padx=10)
        tk.Button(button_frame, text="❌ 取消", command=dialog.destroy, width=12, height=2,
                 bg="#95a5a6", fg="white", font=("Microsoft YaHei", 10, "bold")).pack(side="left", padx=10)
    
    def delete_alarm(self):
        """删除选中的闹钟"""
        selection = self.alarm_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个闹钟")
            return
        
        if messagebox.askyesno("确认删除", "确定要删除这个闹钟吗？"):
            index = self.alarm_tree.index(selection[0])
            self.alarm_manager.delete_alarm(index)
            self.refresh_alarm_list()
            messagebox.showinfo("成功", "闹钟已删除")
    
    def toggle_alarm(self):
        """切换闹钟启用/禁用状态"""
        selection = self.alarm_tree.selection()
        if not selection:
            messagebox.showwarning("警告", "请先选择一个闹钟")
            return
        
        index = self.alarm_tree.index(selection[0])
        new_status = self.alarm_manager.toggle_alarm(index)
        self.refresh_alarm_list()
        
        status_text = "启用" if new_status else "禁用"
        messagebox.showinfo("成功", f"闹钟已{status_text}")
    
    def refresh_alarm_list(self):
        """刷新闹钟列表显示"""
        # 清空现有项
        for item in self.alarm_tree.get_children():
            self.alarm_tree.delete(item)
        
        # 添加闹钟
        alarms = self.alarm_manager.get_all_alarms()
        for alarm in alarms:
            time_str = f"{alarm['hour']:02d}:{alarm['minute']:02d}"
            
            repeat_str = alarm['repeat']
            if repeat_str == "自定义":
                days = ", ".join(alarm['custom_days'])
                repeat_str = f"自定义 ({days})"
            
            ringtone_str = alarm['ringtone']
            status_str = "✅ 启用" if alarm['enabled'] else "❌ 禁用"
            
            self.alarm_tree.insert("", "end", values=(time_str, repeat_str, ringtone_str, status_str))
    
    def manage_ringtones(self):
        """打开铃声管理对话框"""
        dialog = tk.Toplevel(self.root)
        dialog.title("🎵 铃声管理")
        dialog.geometry("550x450")
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (dialog.winfo_width() // 2)
        y = (dialog.winfo_screenheight() // 2) - (dialog.winfo_height() // 2)
        dialog.geometry(f"+{x}+{y}")
        
        # 铃声列表
        list_frame = tk.LabelFrame(dialog, text="📂 当前铃声库", 
                                   font=("Microsoft YaHei", 10, "bold"),
                                   padx=10, pady=10)
        list_frame.pack(fill="both", expand=True, padx=20, pady=10)
        
        ringtone_listbox = tk.Listbox(list_frame, font=("Microsoft YaHei", 10))
        ringtone_listbox.pack(fill="both", expand=True, side="left")
        
        scrollbar = tk.Scrollbar(list_frame, orient="vertical", command=ringtone_listbox.yview)
        scrollbar.pack(side="right", fill="y")
        ringtone_listbox.configure(yscrollcommand=scrollbar.set)
        
        def refresh_ringtone_list():
            ringtone_listbox.delete(0, tk.END)
            for ringtone in self.audio_controller.get_available_ringtones():
                ringtone_listbox.insert(tk.END, ringtone)
        
        refresh_ringtone_list()
        
        # 按钮框架
        button_frame = tk.Frame(dialog)
        button_frame.pack(pady=10)
        
        def add_ringtone():
            files = filedialog.askopenfilenames(
                title="选择铃声文件",
                filetypes=[
                    ("音频文件", "*.mp3 *.wav *.ogg"),
                    ("MP3文件", "*.mp3"),
                    ("WAV文件", "*.wav"),
                    ("OGG文件", "*.ogg"),
                    ("所有文件", "*.*")
                ]
            )
            
            if files:
                count = 0
                for file in files:
                    if self.audio_controller.add_ringtone(file):
                        count += 1
                
                refresh_ringtone_list()
                messagebox.showinfo("成功", f"已成功添加 {count} 个铃声")
        
        def delete_ringtone():
            selection = ringtone_listbox.curselection()
            if not selection:
                messagebox.showwarning("警告", "请先选择一个铃声")
                return
            
            ringtone = ringtone_listbox.get(selection[0])
            if messagebox.askyesno("确认删除", f"确定要删除铃声 '{ringtone}' 吗？"):
                if self.audio_controller.delete_ringtone(ringtone):
                    refresh_ringtone_list()
                    messagebox.showinfo("成功", "铃声已删除")
                else:
                    messagebox.showerror("错误", "删除铃声失败")
        
        def test_ringtone():
            selection = ringtone_listbox.curselection()
            if not selection:
                messagebox.showwarning("警告", "请先选择一个铃声")
                return
            
            ringtone = ringtone_listbox.get(selection[0])
            self.audio_controller.play_ringtone(ringtone, self.alarm_volume, loop=False)
            messagebox.showinfo("试听", f"正在播放: {ringtone}\n\n💡 提示: 如需停止播放，请点击'停止播放'按钮")
        
        def stop_ringtone():
            self.audio_controller.stop_ringtone()
            messagebox.showinfo("已停止", "铃声播放已停止")
        
        tk.Button(button_frame, text="➕ 添加铃声", command=add_ringtone, width=12,
                 bg="#27ae60", fg="white", font=("Microsoft YaHei", 9, "bold")).pack(side="left", padx=5)
        tk.Button(button_frame, text="🗑️ 删除铃声", command=delete_ringtone, width=12,
                 bg="#e74c3c", fg="white", font=("Microsoft YaHei", 9, "bold")).pack(side="left", padx=5)
        tk.Button(button_frame, text="🔊 试听铃声", command=test_ringtone, width=12,
                 bg="#3498db", fg="white", font=("Microsoft YaHei", 9, "bold")).pack(side="left", padx=5)
        tk.Button(button_frame, text="⏹️ 停止播放", command=stop_ringtone, width=12,
                 bg="#95a5a6", fg="white", font=("Microsoft YaHei", 9, "bold")).pack(side="left", padx=5)
        
        # 显示铃声文件夹路径
        path_label = tk.Label(dialog, 
                             text=f"📁 铃声文件夹: {os.path.abspath(self.audio_controller.ringtones_dir)}",
                             font=("Microsoft YaHei", 8), fg="#7f8c8d")
        path_label.pack(pady=5)
        
        info_label = tk.Label(dialog,
                             text="💡 提示: 支持 MP3、WAV、OGG 格式的音频文件",
                             font=("Microsoft YaHei", 8), fg="#3498db")
        info_label.pack(pady=2)
